<template>
  <div class="user-management-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="info" @click="goBack" class="action-button back-button">
        <el-icon><ArrowLeft /></el-icon> 返回
      </el-button>
      <el-button type="primary" @click="add" class="action-button">
        <el-icon><Plus /></el-icon> 新增
      </el-button>
      <el-button type="primary" class="action-button">
        <el-icon><Upload /></el-icon> 导入
      </el-button>
      <el-button type="primary" class="action-button">
        <el-icon><Download /></el-icon> 导出
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="search"
          placeholder="请输入搜索内容"
          class="search-input"
          clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="load" class="search-button">
        <el-icon><Search /></el-icon> 查询
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        border
        stripe
        class="data-table"
        style="width: 100%"
    >
      <el-table-column prop="id" label="ID" sortable />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="sex" label="性别" />
      <el-table-column prop="address" label="地址" />
      <el-table-column fixed="right" label="操作" min-width="140">
        <template #default="scope">
          <el-button
              link
              type="success"
              @click="fetchTodos(scope.row.todoList)"
              class="action-icon-button"
          >
            <el-icon><List /></el-icon> 查看待办列表
          </el-button>
          <el-button
              link
              type="primary"
              @click="handleEdit(scope.row)"
              class="action-icon-button"
          >
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-popconfirm
              title="确认删除吗？"
              @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button type="text" class="action-icon-button delete-button">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-bar">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="form.id ? '编辑用户' : '新增用户'"
        width="500"
        class="user-form-dialog"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" style="width: 300px" />
        </el-form-item>
        <el-form-item label="密码" v-if="!form.id">
          <el-input v-model="form.password" type="password" style="width: 300px" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="form.nickname" style="width: 300px" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="form.age" :min="0" :max="150" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
            <el-radio label="未知">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址">
          <el-input type="textarea" v-model="form.address" style="width: 300px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 待办列表对话框 -->
    <!-- 待办列表对话框 -->
    <el-dialog title="用户的待办列表" v-model="todoVis" width="40%">
      <el-table :data="todoList" stripe border>
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="content" label="事项" />
        <el-table-column prop="status" label="状态" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-button
                size="small"
                type="primary"
                @click="handleTodoEdit(scope.row)"
                class="action-icon-button"
            >
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-popconfirm
                title="确认删除该待办事项吗？"
                @confirm="handleTodoDelete(scope.row.id)"
            >
              <template #reference>
                <el-button
                    size="small"
                    type="text"
                    class="action-icon-button delete-button"
                >
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>


<script>
import request from "@/utils/request";
import {
  Plus,
  Upload,
  Download,
  Search,
  List,
  Edit,
  Delete,
  ArrowLeft,
} from "@element-plus/icons-vue";

export default {
  name: "UserManagement",
  components: {
    Plus,
    Upload,
    Download,
    Search,
    List,
    Edit,
    Delete,
    ArrowLeft,
  },
  data() {
    return {
      form: { username: "", password: "", nickname: "", age: null, sex: "", address: "" },
      dialogVisible: false,
      pageSize: 5,
      search: "",
      currentPage: 1,
      total: 0,
      tableData: [],
      todoVis: false,
      todoList: [],
    };
  },
  created() {
    this.load();
  },
  methods: {
    // 编辑待办事项
    handleTodoEdit(todo) {
      // 根据业务逻辑进行编辑操作
      console.log("编辑待办事项:", todo);
      // 你可以弹出编辑对话框，或者修改待办事项状态等
    },

    // 删除待办事项
    handleTodoDelete(id) {
      request
          .delete(`/todo/${id}`)  // 假设待办事项的删除API是这个
          .then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.fetchTodos();  // 重新加载待办事项列表
            } else {
              this.$message.error(res.message || "操作失败");
            }
          })
          .catch(() => {
            this.$message.error("请求失败");
          });
    },
    // 返回上级页面
    goBack() {
      this.$router.go(-1);
    },
    // 获取待办列表
    fetchTodos() {
      request
          .get("/user/usersWithTodoList")
          .then((response) => {
            this.todoList = response.data;
            this.todoVis = true;
          })
          .catch((error) => {
            console.error("请求失败:", error);
          });
    },
    // 加载用户数据
    load() {
      request
          .get("/user", {
            params: {pageNum: this.currentPage, pageSize: this.pageSize, search: this.search},
          })
          .then((res) => {
            if (res.code === 200) {
              this.tableData = [...res.data?.records] || [];
              this.total = res.data?.total || 0;
            } else {
              this.$message.error(res.message || "加载失败");
            }
          })
          .catch(() => {
            this.$message.error("请求失败");
          });
    },

    // 新增用户
    add() {
      this.form = {username: "", password: "", nickname: "", age: null, sex: "", address: ""};
      this.dialogVisible = true;
    },
    // 保存用户
    save() {
      const requestFn = this.form.id ? request.put : request.post;
      requestFn("/user", this.form)
          .then((res) => {
            console.log("服务器返回:", res); // <-- 观察 `res` 的结构
            if (res.code === 200) {
              this.$message.success(this.form.id ? "更新成功" : "新增成功");
              this.dialogVisible = false;
              this.load();
            } else {
              this.$message.error(res.message || "操作失败");
            }
          })
          .catch((err) => {
            console.error("请求失败:", err);
            this.$message.error(err.message || "请求失败，请检查网络或服务器状态");
          });
    },
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.load();
    },
    // 当前页码变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.load();
    },
    // 编辑用户
    handleEdit(row) {
      this.form = {...row};
      this.dialogVisible = true;
    },
    // 删除用户
    handleDelete(id) {
      request
          .delete("/user/" + id)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.load();
            } else {
              this.$message.error(res.msg || "操作失败");
            }
          })
          .catch(() => this.$message.error("请求失败"));
    },
  },
};
</script>

<style scoped>
/* 全局容器 */
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 操作栏 */
.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-button {
  border-radius: 6px;
  padding: 10px 16px;
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.back-button {
  background-color: #909399;
  border-color: #909399;
}

.back-button:hover {
  background-color: #7a7d82;
  border-color: #7a7d82;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
  margin-right: 10px;
  border-radius: 6px;
}

.search-button {
  border-radius: 6px;
  padding: 10px 16px;
  transition: all 0.3s ease;
}

.search-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 数据表格 */
.data-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.data-table th {
  background: #f5f7fa;
  color: #606266;
}

.data-table__row:hover td {
  background-color: #f5f7fa !important;
}

/* 操作列按钮 */
.action-icon-button {
  padding: 8px;
  transition: color 0.3s;
}

.action-icon-button:hover {
  color: #409eff !important;
}

.delete-button:hover {
  color: #f56c6c !important;
}

/* 分页栏 */
.pagination-bar {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 对话框 */
.user-form-dialog {
  border-radius: 8px;
}

.user-form-dialog .el-dialog__header {
  border-bottom: 1px solid #ebeef5;
}

.user-form-dialog .el-form-item__label {
  font-weight: 500;
}

.user-form-dialog .el-input-number {
  width: 100%;
}

.user-form-dialog .el-textarea :deep(.el-textarea__inner) {
  min-height: 80px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
  }

  .action-button {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }

  .search-bar {
    flex-direction: column;
  }

  .search-input {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }

  .search-button {
    width: 100%;
  }
}
</style>